<?php

/*
 *	Framework namespace
 */
namespace Nano
{
	/*
	 *	Caching class
	 *
	 *	@extends \Kernel
	 */
	class Cache extends \Kernel
	{
		/*
		 *	$path	string	Cache directory
		 */
		public $path;
		
		/*
		 *	$extension	string	Cache extension
		 */
		public $extension = '.tmp';
		
		/*
	 	 *	Constructor
		 */
		public function __construct()
		{
			if(empty($this->path))
			{
				$this->path = APPLICATION.DS.'cache';
				
				define('CACHE', $this->path);
			}
			
			if(!Filesystem::is('dir', $this->path))
			{
				throw new \Exception(__CLASS__.': Cache folder does not exists');
			}
			
			if(!Filesystem::is('writeable', $this->path))
			{
				throw new \Exception(__CLASS__.': Cache folder is not writeable');
			}
		}
		
		/*
		 *	Build path to the cache file
		 *
		 *	@param	string	Cache name
		 *	
		 *	@return	string	Full path to cache file
		 */
		public function path($file)
		{
			if(is_array($file))
			{
				$file = implode('.', $file);
			}
			
			$file = Protect::hash($file);
			
			return $this->path.$file.$this->extension;
		}
		
		/*
		 *	Check for cache
		 *
		 *	@param	string	...
		 *
		 *	@return	boolean
		 */
		public function exists()
		{
			return Filesystem::exists($this->path(func_get_args()));
		}
		
		/*
		 *	Save cache
		 *
		 *	@param	mixed	Cache name (array or string)
		 *	@param	string	Cache contents
		 *	@param	boolean	Overwrite exists cache? [optional]
		 *
		 *	@return	boolean
		 */
		public function save($name, $contents, $overwrite_if_exists = true)
		{
			if($this->exists($name))
			{
				if(!$overwrite_if_exists)
				{
					debug(__METHOD__.': Cache file "'.$this->path.'" will be rewritten');
				}
				else
				{
					debug(__METHOD__.': Cache file "'.$this->path.'" already exists');
					
					return false;
				}
			}
			
			return Filesystem::put($this->path($name), $contents);
		}
	}
}